package cn.xiaobai.captcha.config;

import cn.xiaobai.captcha.annotation.CustomConditionalOnProperty;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.StringUtils;

import java.util.Map;


/**
 * 自定义类型匹配条件
 *
 * @Author yangdaji
 * @Date 2024/4/22
 * @PackageName cn.xiaobai.captcha.config
 * @ClassName CustomTypeOnPropertyConditional
 */
public class CustomTypeOnPropertyConditional implements Condition {

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        // 获取自定义条件注解
        Map<String, Object> annotationAttributes = annotatedTypeMetadata.getAnnotationAttributes(CustomConditionalOnProperty.class.getName());
        String propertyName = (String) annotationAttributes.get("name");
        String[] values = (String[]) annotationAttributes.get("havingVale");
        boolean isDefault = (boolean) annotationAttributes.get("isDefault");

        Environment environment = conditionContext.getEnvironment();
        // 获取配置值
        String value = environment.getProperty(propertyName);
        // 如果为null,或者未指定值, 同时指定默认则为 true
        if (StringUtils.isEmpty(value) && isDefault) {
            return true;
        }

        // 否则匹配值, 若未指定匹配的值, 则false
        if (values == null || values.length == 0) {
            return false;
        }

        // 否则匹配到一个则成功
        for (String havingValue : values) {
            if (havingValue.equalsIgnoreCase(value)) {
                return true;
            }
        }
        return false;
    }
}